package de.justphil.tcg.tcgserver.game.states;

import static de.justphil.tcg.tcgserver.commons.logging.TCGLogging.*;

import org.slf4j.Logger;

import de.justphil.tcg.tcgserver.game.GameManager;
import de.justphil.tcg.tcgserver.game.helpers.GameHelper;
import de.justphil.tcg.tcgserver.game.helpers.GameReporter;
import de.justphil.tcg.tcgserver.websockets.TCGWebSocket;
import de.justphil.tcg.tcgserver.commons.i18n.M;
import de.justphil.tcg.tcgserver.websockets.interfaces.TCGAppManageable;
import de.justphil.tcg.tcgserver.websockets.messages.MessageSubject;
import de.justphil.tcg.tcgserver.websockets.messages.TCGMessage;

public class WaitingForPlayers extends GameState {
	private static final Logger log = logger(WaitingForPlayers.class);
	
	@Override
	protected void progress(GameManager gameManager, TCGWebSocket socket, TCGMessage msg, String data) {
		if (MessageSubject.isQuitSubject(msg)) {
			// graceful disconnect
			GameHelper.gracefullyDisconnectPlayer(gameManager, socket);
		}
		else {
			// new player wants to join the game (game-j), try to associate him with the game
			boolean connected = GameHelper.registerConnectedPlayerAndNotifyAll(gameManager, socket, msg);
			
			if (connected) {
				TCGAppManageable tcgApp = gameManager.getTCGAppManageable();
				
				// notify the TCGApplication that a player (re)connected
				tcgApp.signalReconnectedPlayer(gameManager.getPlayerByWebSocket(socket).getPlayerId());
				
				if (gameManager.isReadyToPlay()) {
					log.info("State transition in game '{}': {} -> {}",
							new Object[] { gameManager.getGameId(), this, WaitingForPlayerInteraction.class.getSimpleName() }
					);
					
					// notify the TCGApplication that the game is about to start
					tcgApp.signalNewGameStarted(gameManager.getGameId());
					
					// set this game's state to 'WaitingForPlayerInteraction'
					gameManager.setState(new WaitingForPlayerInteraction());
					
					// tell the players that the game starts
					GameReporter.broadcastGameInfo(gameManager, null, M.GAME_STARTS);
					
					// initialize game mechanics
					log.debug("Initializing game mechanics -> gameManager.getGame().onResume()");
					gameManager.getGame().onResume();
				}
				else {
					log.info("First player joined! gameId => {}, playerId => {}",
							gameManager.getGameId(), msg.getJoinFragment().getPlayerId());
					
					tcgApp.signalFirstPlayerJoined(gameManager.getGameId());
				}
			}
		}
	}

}
